//
//  SendRequest.m
//  NewYiYiPai
//
//  Created by 程明 on 16/5/19.
//  Copyright © 2016年 程明. All rights reserved.
//

#import "SendRequest.h"
//#import "AFNetworking.h"
#import "AFNetworkActivityIndicatorManager.h"


@implementation SendRequest

static AFHTTPSessionManager * manager;

+ (AFHTTPSessionManager *)sharedInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        manager = [AFHTTPSessionManager manager];
        
        
        manager.requestSerializer=[AFJSONRequestSerializer serializer];
        manager.requestSerializer.stringEncoding=NSUTF8StringEncoding;
        
        manager.responseSerializer= [AFJSONResponseSerializer serializer];
        //manager.responseSerializer=[AFHTTPResponseSerializer serializer];
        
        
        manager.requestSerializer.timeoutInterval=10;
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                                  @"text/html",
                                                                                  @"text/json",
                                                                                  @"text/plain",
                                                                                  @"text/javascript",
                                                                                  @"text/xml",
                                                                                  @"image/*"]];
    });
    
    return manager;
    
    
    
}


+(void)getWithURL:(NSString*)url params:(NSDictionary*)params withCookie:(BOOL )isNeed success:(CMResponseSuccess)cmSuccess fail:(CMResponseFail)cmFail
{
    NSString *urlStr=[NSURL URLWithString:url]?url:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
//    AFHTTPSessionManager *manager =[self sharedInstance];
    
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    manager.requestSerializer.stringEncoding=NSUTF8StringEncoding;
    manager.responseSerializer= [AFJSONResponseSerializer serializer];
    //manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval=10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",@"text/html",@"text/json",@"text/plain",@"text/javascript",@"text/xml",@"image/*"]];
    if (isNeed) {
        [manager.requestSerializer setValue:[CoreArchive strForKey:COOKIE]forHTTPHeaderField:@"Cookie"];
    }
   [manager GET:urlStr parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (cmSuccess) {
            cmSuccess(responseObject);
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (cmFail) {
            cmFail(error);
        }
    }];

}

+(void)postWithURL:(NSString*)url params:(NSDictionary*)params withCookie:(BOOL )isNeed success:(CMResponseSuccess)cmSuccess fail:(CMResponseFail)cmFail
{
    NSString *urlStr=[NSURL URLWithString:url]?url:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//     AFHTTPSessionManager *manager=[self sharedInstance];
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    manager.requestSerializer.stringEncoding=NSUTF8StringEncoding;
    manager.responseSerializer= [AFJSONResponseSerializer serializer];
    //manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval=10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",@"text/html",@"text/json",@"text/plain",@"text/javascript",@"text/xml",@"image/*"]];
    if(!params){
        params=[NSDictionary dictionary];
    }
    NSMutableDictionary*dic=[params mutableCopy];
    params=[dic copy];
    
    if (isNeed) {
        [manager.requestSerializer setValue:[CoreArchive strForKey:COOKIE]forHTTPHeaderField:@"Cookie"];
    }
   
    [manager POST:urlStr parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
       
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        int code=[responseObject[@"code"] intValue];
        if(code==-888||code==-999)
        {

        
        }else{
        
            if (cmSuccess) {
            
            
                cmSuccess(responseObject);
        
            }
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (cmFail) {
            cmFail(error);
        }
        
    }];
    
}
+(void)uploadWithImage:(NSData*)image url:(NSString*)url filename:(NSString*)filename name:(NSString*)name  params:(NSDictionary *)params success:(CMResponseSuccess)success fail:(CMResponseFail)fail
{
    
    NSString *urlStr=[NSURL URLWithString:url]?url:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPSessionManager *manager=[self sharedInstance];
    NSMutableDictionary*dic=[params mutableCopy];
    NSString*accesstoken=[[NSUserDefaults standardUserDefaults]objectForKey:@"AccessToken"];
    __block NSDictionary*d=params;
    if(!accesstoken)
    {
         [[[SendRequest alloc]init] sendTheRequestForAccessTokenWithBlock:^{
             NSString*accesstoken=[[NSUserDefaults standardUserDefaults]objectForKey:@"AccessToken"];
             [dic setObject:accesstoken forKey:@"accesstoken"];
             d=[dic copy];
             [manager POST:urlStr parameters:d constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                 
                 [formData appendPartWithFileData:image name:name fileName:filename mimeType:@"image/jpeg"];
                 
             } progress:^(NSProgress * _Nonnull uploadProgress) {
                 
             } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                 
                 success(responseObject);
                 
             } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                 fail(error);
             }];
         }];
        return;
    }
    [dic setObject:accesstoken forKey:@"accesstoken"];
    params=[dic copy];
    [manager POST:urlStr parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

        [formData appendPartWithFileData:image name:name fileName:filename mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        int code=[responseObject[@"code"] intValue];
        if(code==-888||code==-999)
        {
            [[[SendRequest alloc]init] sendTheRequestForAccessTokenWithBlock:^{
                NSString*accesstoken=[[NSUserDefaults standardUserDefaults]objectForKey:@"AccessToken"];
                [dic setObject:accesstoken forKey:@"accesstoken"];
                d=[dic copy];
                [manager POST:urlStr parameters:d constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                    
                    [formData appendPartWithFileData:image name:name fileName:filename mimeType:@"image/jpeg"];
                    
                } progress:^(NSProgress * _Nonnull uploadProgress) {
                    
                } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    
                    success(responseObject);
                    
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    fail(error);
                }];
            }];
        }else{
        success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
    
}

+(void)downloadWithUrl:(NSString *)url saveToPath:(NSString *)imageName  success:(CMResponseSuccess )success failure:(CMResponseFail )fail
{
    NSString *urlStr=[NSURL URLWithString:url]?url:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    AFHTTPSessionManager *manager=[self sharedInstance];
    
   NSURLSessionDownloadTask *downloadTask =[manager downloadTaskWithRequest:downloadRequest progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:imageName];
        
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        if(success)
        {
            success(response);
        }
        
    }];
    [downloadTask resume];
    
}

+ (BOOL)isExistenceNetwork
{
    
    BOOL isExistenceNetwork=NO;
    Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    switch([reachability currentReachabilityStatus]){
        
        case ReachableViaWiFi: isExistenceNetwork = YES;
            break;
        default:
            isExistenceNetwork = NO;
            break;
            
    }
    return isExistenceNetwork;
}

+ (void)isHaveNetworkWithBlock:(void(^)(BOOL isHave))cheakBlock
{
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        BOOL isExistenceNetwork;
        switch (status) {
            case -1:
                //NSLog(@"未知网络");
                break;
            case 0:
                //NSLog(@"网络不可达");
                break;
            case 1:
                //NSLog(@"GPRS网络");
                break;
            case 2:
                //NSLog(@"wifi网络");
                break;
            default:
                break;
        }
        if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            isExistenceNetwork=YES;
        }else
        {
            isExistenceNetwork=NO;
        }
        cheakBlock(isExistenceNetwork);
    }];

    
}

+(void)getAccesstokenWithURL:(NSString*)url params:(NSDictionary*)params success:(CMResponseSuccess)cmSuccess fail:(CMResponseFail)cmFail
{
    NSString *urlStr=[NSURL URLWithString:url]?url:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPSessionManager *manager=[self sharedInstance];
    
    [manager POST:urlStr parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (cmSuccess) {
            
            cmSuccess(responseObject);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (cmFail) {
            cmFail(error);
        }
        
    }];
    
}

-(void)sendTheRequestForAccessTokenWithBlock:(void(^)(void))successBlock
{
    NSString*url=[NSString stringWithFormat:@"%@/Accesstoken/get_access_token",URL_HOST];
    NSTimeInterval time=[[NSDate date] timeIntervalSince1970];
    NSInteger timeTwo=(NSInteger)time;
    NSString*timespan=[NSString stringWithFormat:@"%ld",timeTwo];
    
    NSString*sign=[MD5Tool md5WithString:[NSString stringWithFormat:@"YK%@2y0s1k7t",timespan]];
    
    NSDictionary*dic=@{@"timespan":timespan,@"sign":sign};
    [SendRequest getAccesstokenWithURL:url params:dic success:^(id response) {
        NSString*accesstoken=response[@"data"];
        [[NSUserDefaults standardUserDefaults]setObject:accesstoken forKey:@"AccessToken"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        NSLog(@"response=%@",response);
        successBlock();
    } fail:^(NSError *error) {
        
    }];
}

@end
